package com.lanmaoly.web.server.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanmaoly.web.common.exception.ArbitrationException;
import com.lanmaoly.web.server.dao.SellerTemporaryMapper;
import com.lanmaoly.web.server.dao.SysUserMapper;
import com.lanmaoly.web.server.dao.TbUserMapper;
import com.lanmaoly.web.server.entity.PageResult;
import com.lanmaoly.web.server.entity.Result;
import com.lanmaoly.web.server.pojo.SellerTemporaryEntity;
import com.lanmaoly.web.server.pojo.SysUserEntity;
import com.lanmaoly.web.server.pojo.SysUserRoleEntity;
import com.lanmaoly.web.server.pojo.TbUser;
import com.lanmaoly.web.server.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 服务实现层
 *
 * @author Administrator
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SellerTemporaryMapper sellerTemporaryMapper;

    /**
     * 查询全部
     */
    @Override
    public List<TbUser> findAll() {
        return userMapper.findAll();
    }

    /**
     * 按分页查询
     */
    @Override
    public PageResult findPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page page = null;
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 增加
     */
    @Override
    public void add(TbUser user) {
        TbUser tbUser = userMapper.selectByUsername(user.getUsername());
        if (tbUser != null) {
            throw new ArbitrationException("用户名已存在");
        }
        Date date = new Date();
        user.setCreated(date);
        user.setUpdated(date);
        user.setSourceType("1");
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insertSelective(user);
    }


    /**
     * 修改
     */
    @Override
    public void update(TbUser user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 根据ID获取实体
     *
     * @param id
     * @return
     */
    @Override
    public TbUser findOne(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 批量删除
     */
    @Override
    public void delete(Long[] ids) {
        for (Long id : ids) {
            userMapper.deleteByPrimaryKey(id);
        }
    }


    @Override
    public PageResult findPage(TbUser user, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<TbUser> page = null;
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public void updateLastLoginTime(TbUser tbUser) {
        userMapper.updateLastLoginTime(tbUser);
    }

    @Override
    public Result resetPassword(TbUser user) {
        TbUser tbUser = userMapper.selectByUsername(user.getUsername());
        if (tbUser == null) {
            return Result.fail("用户名错误");
        }
        String question = tbUser.getQuestion();
        String answer = tbUser.getAnswer();
        if (user.getQuestion().equals(question) && user.getAnswer().equals(answer)) {
            TbUser userdb = new TbUser();
            userdb.setId(tbUser.getId());
            userdb.setPassword(passwordEncoder.encode(user.getPassword()));
            userMapper.updateByPrimaryKeySelective(userdb);
            return Result.success("重置密码成功");
        }
        return Result.fail("密保问题或答案错误");
    }

    @Override
    public void registerSettle(SellerTemporaryEntity tbSeller) {
        SysUserEntity sysUserEntity = sysUserMapper.getByUsername(tbSeller.getUsername());
        if (sysUserEntity != null) {
            throw new ArbitrationException("该用户名已被注册:" + tbSeller.getUsername());
        }
        String salt = RandomStringUtils.randomAlphanumeric(20);
        String password = this.sha256(tbSeller.getPassword(), salt);
        SysUserEntity entity = new SysUserEntity();
        entity.setCreateTime(new Date());
        entity.setEmail(tbSeller.getEmail());
        entity.setMobile(tbSeller.getMobile());
        entity.setUsername(tbSeller.getUsername());
        entity.setPassword(password);
        entity.setStatus(1);
        entity.setSalt(salt);
        entity.setDeptId(4L);
        sysUserMapper.save(entity);

        tbSeller.setSellerId(entity.getUserId().toString());
        tbSeller.setStatus("1");
        tbSeller.setCreateTime(entity.getCreateTime());
        sellerTemporaryMapper.save(tbSeller);

        // 权限表
        SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
        // userid
        sysUserRoleEntity.setUserId(entity.getUserId());
        // 普通商家
        sysUserRoleEntity.setRoleId(3L);
        sysUserMapper.saveRole(sysUserRoleEntity);
    }

    @Override
    public TbUser selectByName(String name) {
        return userMapper.selectByUsername(name);
    }

    private String sha256(String password, String salt) {
        return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
    }

    /**
     * 加密算法
     */
    public final static String hashAlgorithmName = "SHA-256";
    /**
     * 循环次数
     */
    public final static int hashIterations = 16;
}
